package fragments;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.homework7.Config;
import com.example.homework7.MyDBHelper;
import com.example.homework7.R;

public class SqliteFragment {


    /**
     * sqlite基本操作类
     * created by howie 2021/05/06
     */
    public class SqliteFragment extends Fragment {
        private static final String TAG = "SqliteFragment";
        private static SqliteFragment fragment;

        private EditText mEtName;
        private EditText mEtAge;
        private Button mBtnAdd;
        private Button mBtnUnder18years;
        private TextView mTvShow;

        private String name;
        private int age;

        private SqliteFragment() {
        }

        public static SqliteFragment newInstance() {
            if(fragment == null){
                fragment = new SqliteFragment();
            }
            return fragment;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_sqlite, container, false);
            initView(view);

            initEvent(view);


            return view;
        }

        private void initEvent(View view) {
            MyDBHelper dbHelper = new MyDBHelper(getContext(), "sqlite.db", null, Config.SQLITE_VERSION);


            mBtnAdd.setOnClickListener(new View.OnClickListener() {//添加
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: " + R.string.add_text);
                    //获取输入框的内容
                    Boolean flag = getEditTextContent();
                    if(flag && !name.equals("")){
                        //数据库的操作
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        Log.d(TAG, "onClick: username = " + name);
                        Log.d(TAG, "onClick: age = " + age);
                        values.put(Config.USER_NAME, name);
                        values.put(Config.USER_AGE, age);
                        long ret = db.insert(Config.DATABASE_TABLE_USERS, null, values);
                        String msg = ret == -1 ? "添加失败" : "添加成功";
                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "onClick: msg = " + msg);
                        db.close();
                    }else {
                        Toast.makeText(getContext(), "添加失败，请查看名字输入是否正确", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            mBtnUnder18years.setOnClickListener(new View.OnClickListener() {//查询小于18岁的
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: " + R.string.under_18_years_text);
                    //数据库的操作
                    SQLiteDatabase db = dbHelper.getReadableDatabase();
                    String selection = Config.USER_AGE + "<?";
                    String[] args = new String[]{"18"};
                    Log.d(TAG, "onClick: selection = " + selection);

                    StringBuilder builder = new StringBuilder();
                    Cursor cursor = db.query(Config.DATABASE_TABLE_USERS, null, selection, args, null, null, null);
                    while (cursor.moveToNext()){
                        long id = cursor.getLong(cursor.getColumnIndex(Config.USER_ID));
                        String name = cursor.getString(cursor.getColumnIndex(Config.USER_NAME));
                        int age = cursor.getInt(cursor.getColumnIndex(Config.USER_AGE));
                        builder.append("id: ").append(id)
                                .append("   username: ").append(name)
                                .append("   age: ").append(age)
                                .append("\n");
                        Log.d(TAG, "onClick: builder.tostring = " + builder.toString());

                    }
                    mTvShow.setText(builder.toString());
                }
            });
        }

        /**
         * 获取输入框里的内容
         */
        private boolean getEditTextContent() {
            try {
                name = mEtName.getText().toString();
                age = Integer.parseInt(mEtAge.getText().toString());

                Log.d(TAG, "getEditTextContent: " + mEtName.getText().toString());
                Log.d(TAG, "getEditTextContent: " + mEtAge.getText().toString());
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "输入框内容获取失败，请查看输入是否正确", Toast.LENGTH_SHORT).show();
                return false;
            }

            return true;
        }

        private void initView(View view) {
            mEtName = view.findViewById(R.id.et_input_name_by_sqlite);
            mEtAge = view.findViewById(R.id.et_input_age_by_sqlite);
            mBtnAdd = view.findViewById(R.id.btn_add_by_sqlite);
            mBtnUnder18years = view.findViewById(R.id.btn_under_18_years_by_sqlite);
            mTvShow =view.findViewById(R.id.tv_show_by_sqlite);
        }
    }
}
